package userRecycleModuleApi

import (
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/enums"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/model"
	"KumquatDrivesServices/utils"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

type deleteRecoverFileRequest struct {
	FileIds []model.SnowflakeIdType `json:"fileIds" binding:"required"`
}

func (UserRecycleModuleApi) DeleteRecoverFile(c *gin.Context) {
	var req deleteRecoverFileRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		logrus.Errorf("DeleteRecoverFile ShouldBindJSON err: %+v", err)
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	userId := utils.GetUserId(c)
	var recoverFileList []model.FileModel
	recoverFileQuery := global.DB.Where("id in (?) and user_id=? and del_flag=?", req.FileIds, userId, enums.RecycleBin)
	if err := recoverFileQuery.Find(&recoverFileList).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.Errorf("DeleteRecoverFile recoverFileQuery err: %+v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	if len(recoverFileList) == 0 {
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	var TheTotalRecoverFileSize int64 = 0
	var recoverFileIdList []model.SnowflakeIdType
	for _, recoverFile := range recoverFileList {
		if recoverFile.IsFolder == enums.Folder {
			result, err := utils.FindAllSubFolderFileList(userId, recoverFile.ID, enums.Forbidden)
			if err != nil {
				logrus.Errorf("FindAllSubFolderFileList err: %+v", err)
				res.FailWithCode(res.SYS_ERR, c)
				return
			}
			for _, file := range result {
				if file.IsFolder == enums.Folder {
					recoverFileIdList = append(recoverFileIdList, file.ID)
					continue
				}
				TheTotalRecoverFileSize = TheTotalRecoverFileSize + file.FileSize
			}
			recoverFileIdList = append(recoverFileIdList, recoverFile.ID)
			continue
		}
		TheTotalRecoverFileSize = TheTotalRecoverFileSize + recoverFile.FileSize
		recoverFileIdList = append(recoverFileIdList, recoverFile.ID)
	}
	var userModel model.UserModel
	userModel.ID = userId
	tx := global.DB.Begin()
	txQuery := tx.Model("file_models").Where("id in (?) and user_id=?", recoverFileIdList, userId)
	if err := txQuery.Update("del_flag=?", enums.Deleted).Error; err != nil {
		tx.Rollback()
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	if err := userModel.UpdateUserCapacity(TheTotalRecoverFileSize, enums.SubtractUserCapacity); err != nil {
		tx.Rollback()
		logrus.Errorf("UpdateUserCapacity err: %+v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		logrus.Errorf("Commit err: %+v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	res.OkWithData(res.EmptyData, c)
}
